<?php
/************************
 *  Codenova.pl Project
 *  Created by: Kamil Mrzygłód
 *
 *  (c) 2013 by Codenova.pl
 *  All Right Reserved
 ***********************/

namespace Modules\GotchaAdmin\Controllers;

use Gotcha\App\Extensions\HttpExtension;
use Gotcha\App\Framework\Controller;
use GotchaDatabase\GotchaUsersQuery;

class DefaultController extends Controller {
    public function Index() {
        if(!isset($_SESSION['userId']) || empty($_SESSION['userId'])) {
            return $this->Login();
        }

        return parent::View();
    }

    private function Login() {
        return parent::View();
    }

    public function LoginPost() {
        $http = new HttpExtension();

        if(!isset($_POST['Login']) || !isset($_POST['Password']) || empty($_POST['Login']) || empty($_POST['Password'])) {
            //header('Location: '.parent::UrlContent('/'));
            exit;
        } else {
            $login = $_POST['Login'];
            $password = $_POST['Password'];
        }

        if(strlen($login) > 15 || strlen($password) > 255) {
            exit;
        }

        // After validation we can attempt to login user
        $users = GotchaUsersQuery::create()
                    ->findOneByLogin($login);

        if(is_null($users)) {
            exit;
        }

        // Compare given password with one stored in database
        if(crypt($password, $users->getSalt()).$users->getSalt() == $users->getPassword().$users->getSalt()) {
            // User passed password validation, create a session
            // and redirect him
            $_SESSION['userId'] = session_id();
            header('Location: '.$http->resolveAbsoluteUrl().parent::UrlContent('/Admin'));
            exit;
        } else {
            echo 'Error';
            exit;
        }
    }
}